package com.fowo.api.jewelry.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.service.impl.DatainterfaceServiceImpl;
import com.fowo.api.datainterface.util.JsonUtil;
import com.fowo.api.entity.*;
import com.fowo.api.jewelry.mapper.SyncJmOrderMapper;
import com.fowo.api.model.nav.sell.order.NavSellOrderVo;
import com.fowo.api.model.nav.sell.order.detail.NavSellOrderDetailItemVo;
import com.fowo.api.model.nav.sell.order.platform.NavSellOrderPlatformItemVo;
import com.fowo.api.model.tmp.jm.goods.order.TmpJmGoodsOrderItemVo;
import com.fowo.api.model.tmp.jm.goods.order.TmpJmGoodsOrderSearchParamPo;
import com.fowo.api.service.impl.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@DS("ds24")
public class SyncJewelryOrderService {
    @Resource
    private DatainterfaceServiceImpl datainterfaceService;
    @Resource
    private TmpJmGoodsOrderServiceImpl tmpJmGoodsOrderService;
    @Resource
    private TmpJmOrderChildrenServiceImpl tmpJmOrderChildrenService;
    @Resource
    private NavSellOrderServiceImpl navSellOrderService;
    @Resource
    private NavSellOrderPlatformServiceImpl navSellOrderPlatformService;
    @Resource
    private SysCountryServiceImpl sysCountryService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private SyncJmOrderMapper syncJmOrderMapper;

    @Transactional(rollbackFor = Exception.class)
    public void syncOrder() throws Exception {
        syncJmOrderMapper.deleteTmpJmGoodsOrder();
        syncJmOrderMapper.deleteTmpJmOrderChildren();
//        tmpTiktokOrderFaceService.remove(null);
        getOrderList();
        log.info("拉取订单数据完成");
        saveNavSellOrder();
        log.info("插入订单数据完成");

//        navSellOrderService.splitTask();
//        log.info("订单数据拆分检测完成");
//        navSellOrderService.joinTask();
//        log.info("订单数据合并检测完成");
    }

    public void getOrderList(){
        final List<ShopInfo> shopInfoList = shopInfoService.list(Wrappers.lambdaQuery(ShopInfo.class).eq(ShopInfo::getPlatform, "Jewelry"));


        JSONObject param = new JSONObject();
        param.put("status", "2");
        param.put("current", 1);
        param.put("pageSize", 100000);
        final Object res = datainterfaceService.executeInterface(null, "EC00518", null, param, null);
//        System.out.println("独立站订单返回参数："+res);
        if (ObjUtil.isEmpty(res)) {
            log.error("独立站订单接口无响应,请重试!");
        }else {
            final JSONArray jsonArray = JsonUtil.getJsonToBeanSafe(res, JSONArray.class);
            List<TmpJmGoodsOrder> orderList = new ArrayList<>();
            List<TmpJmOrderChildren> orderChildrenList = new ArrayList<>();
            for(int i = 0 ; i < jsonArray.size() ; i++){
                final cn.hutool.json.JSONObject jsonObject = jsonArray.getJSONObject(i);
                final TmpJmGoodsOrder tmpJmGoodsOrder = jsonArray.get(i, TmpJmGoodsOrder.class);
                tmpJmGoodsOrder.setCreateTime(new Date());
                if(CollectionUtil.isNotEmpty(shopInfoList)){
                    tmpJmGoodsOrder.setSid(shopInfoList.get(0).getId());
                }
                orderList.add(tmpJmGoodsOrder);

                final cn.hutool.json.JSONObject children = jsonObject.getJSONObject("children");
                final String records = children.getStr("records");
                final List<TmpJmOrderChildren> TmpJmOrderChildrenList = JsonUtil.getJsonToList(records, TmpJmOrderChildren.class);
                orderChildrenList.addAll(TmpJmOrderChildrenList);
            }
            tmpJmGoodsOrderService.saveBatch(orderList);
            tmpJmOrderChildrenService.saveBatch(orderChildrenList);
        }
    }

    public void saveNavSellOrder() throws Exception {
        TmpJmGoodsOrderSearchParamPo search = new TmpJmGoodsOrderSearchParamPo();
        search.setDisableDataPremissions(true);
        final List<TmpJmGoodsOrderItemVo> orderItemVoList = tmpJmGoodsOrderService.search(search);
        for(TmpJmGoodsOrderItemVo order : orderItemVoList){
            NavSellOrder oldNavSellOrder = getNavSellOrderByPlatformOrderId(order.getOrderId());
            if(null == oldNavSellOrder){
                NavSellOrderVo navSellOrder = buildNavSellOrder(order);
                navSellOrderService.create(navSellOrder);
            }
        }
    }

    /**
     * 根据平台单号获取订单
     * @param platformOrderId
     * @return
     */
    public NavSellOrder getNavSellOrderByPlatformOrderId(String platformOrderId) {
        NavSellOrderPlatform navSellOrderPlatform = navSellOrderPlatformService.getOne(Wrappers.lambdaQuery(NavSellOrderPlatform.class)
                .eq(NavSellOrderPlatform::getPlatformOrderId,platformOrderId)
                .eq(NavSellOrderPlatform::getPlatform,"Jewelry"));
        if(null == navSellOrderPlatform){
            return null;
        }
        NavSellOrder navSellOrder = navSellOrderService.getById(navSellOrderPlatform.getParentNavSellOrder());
        return navSellOrder;
    }

    /**
     * 构建订单管理数据
     * @param jmOrder
     * @return
     */
    public NavSellOrderVo buildNavSellOrder(TmpJmGoodsOrderItemVo jmOrder) {
        NavSellOrderVo navSellOrder = new NavSellOrderVo();

        final List<TmpJmOrderChildren> jmOrderChildrenList = tmpJmOrderChildrenService.list(Wrappers.lambdaQuery(TmpJmOrderChildren.class).eq(TmpJmOrderChildren::getOrderId, jmOrder.getId()));
        final List<SysCountry> countries = sysCountryService.list(Wrappers.lambdaQuery(SysCountry.class).likeRight(SysCountry::getCountryCn, jmOrder.getShippingCountry()));
        // 基础信息
        navSellOrder.setShopInfo(jmOrder.getSid());
        navSellOrder.setCurrency(jmOrder.getCurrencyExchangeRateId() == null ? null : jmOrder.getCurrencyExchangeRateId().toString());
        navSellOrder.setType(jmOrderChildrenList.size() == 1?"1":"2"); // 1一件一单；2一件多单
        navSellOrder.setStatus("1");
//        navSellOrder.setSite(); //独立站没有站点
        navSellOrder.setSplitType("1");
        navSellOrder.setPaymentWay(jmOrder.getPaymentMethod());
        navSellOrder.setBuyerName(jmOrder.getConsignee());
        navSellOrder.setDeliveryReceipt(jmOrder.getConsignee());
        navSellOrder.setDeliveryZipCode(jmOrder.getShippingZipCode());
        navSellOrder.setDeliveryPhone(jmOrder.getPhone());
        navSellOrder.setDeliveryCountry(CollectionUtil.isEmpty(countries)?null:countries.get(0).getId());
        navSellOrder.setDeliveryProvince(jmOrder.getShippingState());
        navSellOrder.setDeliveryCity(jmOrder.getShippingCity());
        navSellOrder.setDeliveryArea(jmOrder.getShippingStreet());
        navSellOrder.setDeliveryAddressType("1");
        navSellOrder.setDeliveryAddress1(jmOrder.getShippingAddress());
//        if(StrUtil.isNotBlank(sheinOrder.getTaxNo())){
//            navSellOrder.setDeliveryRecipientTaxType("5");
//            navSellOrder.setDeliveryRecipientTaxNo("");
//        }
        navSellOrder.setDeliveryType("2");
        navSellOrder.setDeliveryCodeOrder("0");
        // 平台信息
        NavSellOrderPlatformItemVo navSellOrderPlatform = new NavSellOrderPlatformItemVo();
        navSellOrderPlatform.setPlatformId(jmOrder.getId().toString());
        navSellOrderPlatform.setPlatformOrderId(jmOrder.getOrderId());
//        navSellOrderPlatform.setCancelTime(jmOrder.getLastUpdateTime());
//        navSellOrderPlatform.setLatestShipTime();
        navSellOrderPlatform.setSource("1");
        navSellOrderPlatform.setPaymentStatus("1");
        navSellOrderPlatform.setPaymentTime(jmOrder.getPaymentTime());
        navSellOrderPlatform.setPlatform("Jewelry");
        navSellOrderPlatform.setPurchaseTime(jmOrder.getOrderTime());
//        navSellOrderPlatform.setShippingStatus("");
//        navSellOrderPlatform.setStatus("");
        navSellOrderPlatform.setCountry(CollectionUtil.isEmpty(countries)?null:countries.get(0).getId());
        List<NavSellOrderPlatformItemVo> platformList = new ArrayList<>();
        platformList.add(navSellOrderPlatform);
        navSellOrder.setPlatform(platformList);

//        boolean isPari = true; //是否配对商品
        // 产品信息
        NavSellOrderDetailItemVo navSellOrderDetail;
        List<NavSellOrderDetailItemVo> sellOrderDetailList = new ArrayList<>();
        for(TmpJmOrderChildren orderGoods : jmOrderChildrenList){
            if(StrUtil.isBlank(orderGoods.getGoodsCode())){
                continue;
            }

            navSellOrderDetail = new NavSellOrderDetailItemVo();
            navSellOrderDetail.setShopInfo(jmOrder.getSid());
            navSellOrderDetail.setPlatformOrderId(jmOrder.getOrderId());
            navSellOrderDetail.setItemFromName("1");
            navSellOrderDetail.setGoodsTitle(orderGoods.getName());
            navSellOrderDetail.setGoodsCode(orderGoods.getGoodsId().toString());
            navSellOrderDetail.setMsku(orderGoods.getGoodsCode());
//            navSellOrderDetail.setAttribute(variantAttr);
//            navSellOrderDetail.setSalesRevenueAmount();//销售收益
            navSellOrderDetail.setPrice(orderGoods.getPrice());
            navSellOrderDetail.setQuantity(orderGoods.getQuantity());
//            navSellOrderDetail.setDiscount();
            navSellOrderDetail.setAmount(orderGoods.getOriginPrice());
            navSellOrderDetail.setTransactionCost(BigDecimal.ZERO);
//            navSellOrderDetail.setOtherAmount(); // 平台其他费
//            navSellOrderDetail.setSaleTax();
            navSellOrderDetail.setPlatformStatus("1");

            sellOrderDetailList.add(navSellOrderDetail);
        }
        navSellOrder.setProduct(sellOrderDetailList);

        return navSellOrder;
    }

}
